//
//  PreferenceController.m
//  FlickrImport
//
//  Created by Sandeep Chayapathi on 1/8/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "PreferenceController.h"

NSString *MEFlickrFrob = @"Frob";
NSString *MEFlickrToken = @"Token";
extern NSString *MEFlickrUserName = @"userName";
extern NSString *MEFlickrUserId = @"userId";

@implementation PreferenceController

- (id) init {
    self = [super initWithWindowNibName:@"Preferences"];
    return self;
}

- (void) windowDidLoad {
    NSLog(@"Nib file loaded");
}

- (void)awakeFromNib {
    [tokenButton setEnabled:FALSE];
    [tokenTitle setEnabled:FALSE];
    
     api_key = @"8f05692f343813719b916b41415e9720";
     shared_secret = @"f96644c5c77e07f0";
     
     context = [[OFFlickrContext contextWithAPIKey:api_key 
                                      sharedSecret: shared_secret] retain];
     
     invoc = [[OFFlickrInvocation invocationWithContext:context
                                               delegate: self] retain];
}


- (IBAction) authenticate:(id)sender {
    [self getFrob];
}

- (IBAction) authenticateToken:(id)sender; {
    [self getToken];
}

- (NSString *) frob; {
    return frob;
}

- (void) frob: (NSString *) str; {
    frob = str;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:frob forKey:MEFlickrFrob];
}

- (NSString *) token; {
    return token;
}
- (void) token: (NSString *) d; {
    token = d;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:token forKey:MEFlickrToken];
}

- (void)flickrInvocation:(OFFlickrInvocation*)invocation errorCode:(int)errcode errorInfo:(id)errinfo {
    NSString *userinfo = [invoc userInfo];
    
	if (errcode == OFConnectionCanceled) {
		NSLog(@"FlickrImport: canceled! state=%@", userinfo);
		return;
	}
	
	NSLog(@"FlickrImport: error! code=%d, errinfo=%@, state=%@", errcode, errinfo, userinfo);
    
	NSString *errmsg=[NSString stringWithFormat:@"%@ (error code %d)",
		((errcode < 0) ? @"Internal error" : @"Flickr API error"), errcode];    
    
    NSString *informText = nil;
    
	[[NSAlert alertWithMessageText:errmsg
                     defaultButton:@"Go back"
                   alternateButton:nil
                       otherButton:nil
         informativeTextWithFormat:informText
        ] runModal];	    
}

- (void)flickrInvocation:(OFFlickrInvocation*)invocation didFetchData:(NSXMLDocument*)xmldoc; {
    NSString *userInfo = [invoc userInfo];
    
    NSLog(@"FlickrImport: going to invoke selector for: %@:", userInfo);
    
    SEL flickrSel = NSSelectorFromString([userInfo stringByAppendingString:@":"]);
    [self performSelector:flickrSel withObject:xmldoc];
    
}

// Invoke Flickr Requests

- (void) getFrob; {
    [invoc setUserInfo: @"getFrob"];
    [invoc callMethod:@"flickr.auth.getFrob"
            arguments:nil];
}

- (void) getToken; {
    
    NSLog(@"FlickrImport: got frob: %@ - now getting token", 
          [self frob]);	
    
    [invoc setUserInfo:@"getToken"];
	[invoc callMethod:@"flickr.auth.getToken" 
            arguments:[NSArray arrayWithObjects:@"frob", [self frob] , nil]];    
}

// Handle Flickr Results

- (void) getFrob: (NSXMLDocument*)xmldoc; {    
    NSDictionary *payload = [xmldoc flickrDictionaryFromDocument];
    
    [self frob: [[NSString stringWithString: [payload valueForKeyPath:@"frob.$"]] retain]];
    
    NSLog(@"FlickrImport: got frob: %@ - now authenticating", [self frob]);
    
    NSString *authurl=[context prepareLoginURL:[self frob] permission:@"read"];
	system([[NSString stringWithFormat:@"open '%@'", authurl] UTF8String]);
    
    [tokenButton setEnabled:TRUE];
    [tokenTitle setEnabled:TRUE];
    
}

- (void) getToken: (NSXMLDocument*)xmldoc; {
	NSDictionary *payload = [xmldoc flickrDictionaryFromDocument];    
    [self token: [[[NSDictionary dictionaryWithDictionary:payload] 
                    valueForKeyPath:@"auth.token.$"] retain]];
    
    NSDictionary *user = [[NSDictionary dictionaryWithDictionary:payload] 
                            valueForKeyPath:@"auth.user"];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:[user valueForKey:@"_username"] forKey: MEFlickrUserName];
    [defaults setValue:[user valueForKey:@"_nsid"] forKey:MEFlickrUserId];

    [self close];
}
@end
